<?php
//require_once IA_ROOT.'/addons/goouc_class/inc//phpexcel/PHPExcel.php';
global $_W, $_GPC;
$op = trim(empty($_GPC['op']) ? 'list' : $_GPC['op']);
$weid = $_W['uniacid'];//店铺id
$sonid = $_GPC['sonid'];//章节id
$lid = $_GPC['lid'];//课程id
$types_config = array('1' => '判断题', '2' => '单选题', '3' => '多选题', '4' => '填空题');
$answer_array = array('A', 'B', 'C', 'D', 'E', 'F');
$lessontitle = pdo_get('goouc_class_lesson', array('id' => $lid), array('title'));
$sontitle = pdo_get('goouc_class_son', array('id' => $sonid), array('title'));
if ($op == 'list') {
    $psize = 10;
    $paixu = empty($_GPC['paixu']) ? 1 : $_GPC['paixu'];
    $pageindex = max(1, $_GPC['page']);
    $limit = ' LIMIT ' . ($pageindex - 1) * $psize . ',' . $psize;
    if ($paixu == 1) {
        $order = " ORDER BY `sort` DESC";
    } elseif ($paixu == 2) {
        $order = " ORDER BY `sort` ASC";
    }
    $sql = 'SELECT id,lessonid,sonid,type,question,thumb,answer,items,img_items,analysis,isimg,status,sort FROM' . tablename($this->t_practice) . 'WHERE weid = :weid AND lessonid = :lessonid AND sonid = :sonid AND is_delete = :is_delete ' . $order . $limit;
    $practicelist = pdo_fetchall($sql, array(':weid' => $weid, ':lessonid' => $lid, ':sonid' => $sonid, ':is_delete' => 1));
    foreach ($practicelist as &$v) {
        $v['question'] = strip_tags($v['question']);
        //strip_tags
    }
    $tsql = "SELECT COUNT(*) FROM " . tablename($this->t_practice) . " WHERE weid = :weid AND lessonid = :lessonid AND sonid = :sonid AND is_delete = :is_delete";
    $total = pdo_fetchcolumn($tsql, array(':weid' => $weid, ':lessonid' => $lid, ':sonid' => $sonid, ':is_delete' => 1));
    $page = pagination($total, $pageindex, $psize);
    $num = $total - ($pageindex - 1) * $psize;
    foreach ($practicelist as &$v) {
        if ($v['type'] == 1) {
            if ($v['answer'] == 0) {
                $v['answer'] = '错误';
            } else {
                $v['answer'] = '正确';
            }
        }
        $v['type'] = $types_config[$v['type']];
    }
    include $this->template('web/practice');
} elseif ($op == 'edit') {
    $id = $_GPC['id'];
    $type = $_GPC['type'];
    $order = $_GPC['sort'];
    $isImg = intval($_GPC['isimg']);
    if (!empty($id)) {
        //修改试题
        $item = pdo_fetch("select * from " . tablename('goouc_class_practice') . " where id=:id limit 1", array(":id" => $id));
        if (!empty($item)) {
            $item['items'] = unserialize($item['items']);
            $item['img_items'] = unserialize($item['img_items']);
        }
    }
    if ($_W['ispost']) {
        $is_next = $_GPC['is_next'];
        if (!$_GPC['question']) {
            message("习题题目问题不能为空!", '', "error");
        }
        if (!$_GPC['analysis']) {
            message("习题解析不能为空!", '', "error");
        }
        $insert = array(
            'weid' => $weid,
            'lessonid' => $lid,
            'sonid' => $sonid,
            //'question' =>  htmlspecialchars_decode(strip_tags($_GPC['question'])),
            'type' => $type,
            'sort' => $order,
            //'analysis' => htmlspecialchars_decode(strip_tags($_GPC['analysis'])),
        );
        if ($_W['uniacid'] == 28) {
            $insert['question'] = strip_tags($_GPC['question']);
            $insert['analysis'] = strip_tags($_GPC['analysis']);
        } else {
            $insert['question'] = htmlspecialchars_decode(strip_tags($_GPC['question']));
            $insert['analysis'] = htmlspecialchars_decode(strip_tags($_GPC['analysis']));
        }
        $items = "";
        if ($type == 1) {
            $answer = $_GPC['answer1'];
        } else if ($type == 2) {
            $answer = $_GPC['answer2'];
            foreach ($_GPC['items2'] as $k => &$v) {
                if (trim($v) != "") {
                    $itemsArr2[] = ['o' => $answer_array[$k], 'p' => trim($v)];
                }
            }
            $items = serialize($itemsArr2);
        } else if ($type == 3) {
            $arr = $_GPC['answer3'];
            $answer = implode("", $arr);
            foreach ($_GPC['items3'] as $k => &$v) {
                if (!empty($v)) {
                    $itemsArr3[] = ['o' => $answer_array[$k], 'p' => $v];
                }
            }
            $items = serialize($itemsArr3);
        } else if ($type == 4) {
            $answer = $_GPC['items4'];
        }
        $insert['answer'] = strip_tags($answer);
        $insert['items'] = $items;
        $insert['thumb'] = $_GPC['thumb'];
        $insert['isimg'] = $isImg;
        if ($isImg == 1 && ($type == 2 || $type == 3)) {
            $img_items = array();
            $item_name = "img_items" . $type . "_";
            foreach ($answer_array as $key => $value) {
                if ($_GPC[$item_name . $key]) {
                    $img_items[$key] = ['o' => $answer_array[$key], 'p' => $_GPC[$item_name . $key]];
                }
                if (!empty($_GPC[$item_name . $key . '-old'])) {
                    file_delete($_GPC[$item_name . $key . '-old']);
                }
            }
            $insert['img_items'] = serialize($img_items);
        }
        if (empty($id)) {
            $res = pdo_insert('goouc_class_practice', $insert);
        } else {
            $res = pdo_update('goouc_class_practice', $insert, array('id' => $id));
        }
        if ($is_next) {
            $array = array();
            $array['op'] = 'edit';
            $array['lid'] = $lid;
            $array['sonid'] = $sonid;
            $url = $this->createWebUrl('practice', $array);
        } else {
            $array = array();
            $array['op'] = 'list';
            $array['lid'] = $lid;
            $array['sonid'] = $sonid;
            $url = $this->createWebUrl('practice', $array);
        }
        if ($res) {
            //如果这个课程的这个章节已经有题，也有学生做过了，那么就把学生做题状态改为没有做题，星星也要重新计算
            $sqlrecord = 'SELECT id FROM' . tablename("goouc_class_practice_record") . 'WHERE weid = :weid AND lessonid = :lessonid AND sonid = :sonid AND status = :status ';
            $recordlist = pdo_fetchall($sqlrecord, array(':weid' => $weid, ':lessonid' => $lid, ':sonid' => $sonid, ':status' => 1));
            if ($recordlist) {
                foreach ($recordlist as $rk => $rv) {
                    pdo_update('goouc_class_practice_record', array('status' => 2), array('id' => $rv['id']));
                }
            }
            //把获取的星星也要重新计算
            $sqlstar = 'SELECT id FROM' . tablename("goouc_class_user_star") . 'WHERE weid = :weid AND lessonid = :lessonid AND sonid = :sonid AND status = :status ';
            $starlist = pdo_fetchall($sqlstar, array(':weid' => $weid, ':lessonid' => $lid, ':sonid' => $sonid, ':status' => 1));
            if ($starlist) {
                foreach ($starlist as $rk => $rv) {
                    pdo_update('goouc_class_user_star', array('status' => 2), array('id' => $rv['id']));
                }
            }
            message("习题信息保存成功!", $url, "success");
        } else {
            message("习题信息保存失败!", $url, "error");
        }
    } else {
        include $this->template('web/practice_add');
    }
} elseif ($op == 'cstatus') {
    $id = $_GPC['id'];
    $sta = $_GPC['sta'];
    $data['status'] = $sta;
    $info = pdo_get($this->t_practice, array('id' => $id, 'weid' => $_W['uniacid']), 'status');
    if ($sta == $info['status']) {
        $message = array('success' => 3, 'mess' => '更改失败，请刷新页面后再更改');
    } else {
        $res = pdo_update($this->t_practice, $data, array('id' => $id, 'weid' => $_W['uniacid']));
        if ($res) {
            $message = array('success' => 1, 'mess' => '更改成功');
        } else {
            $message = array('success' => 0, 'mess' => '更改失败');
        }
    }
    echo json_encode($message);
    exit;
} elseif ($op == 'del') {
    $id = $_GPC['id'];
    $info = pdo_get($this->t_practice, array('id' => $id, 'is_delete' => 1, 'weid' => $_W['uniacid']), 'id');
    $array = array();
    $array['op'] = 'list';
    $array['lid'] = $lid;
    $array['sonid'] = $sonid;
    $url = $this->createWebUrl('practice', $array);
    if ($info) {
        $sqlcheck = 'SELECT id FROM' . tablename("goouc_class_practice_record") . 'WHERE weid = :weid AND lessonid = :lessonid AND sonid = :sonid AND status = :status ';
        $checkrecord = pdo_fetchall($sqlcheck, array(':weid' => $weid, ':lessonid' => $lid, ':sonid' => $sonid, ':status' => 1));
        if ($checkrecord) {
            message("已经有学员做过，不能删除", $url, 'error');
        } else {
            $data['is_delete'] = 2;
            $data['status'] = 0;
            $res = pdo_update($this->t_practice, $data, array('id' => $id, 'weid' => $_W['uniacid']));
            message("删除成功", $url, 'success');
        }
    } else {
        message("删除失败，请刷新页面后重试", $url, 'error');
    }
} elseif ($op == 'import') {
    if (checksubmit('submit')) {
        if (!empty($_FILES['room']['name'])) {
            $tmp_file = $_FILES['room']['tmp_name'];
            $file_types = explode(".", $_FILES['room']['name']);
            $file_type = $file_types[count($file_types) - 1];
            /*判别是不是.xls文件，判别是不是excel文件*/
            if (strtolower($file_type) != "xls" && strtolower($file_type) != "xlsx") {
                message('类型不正确，请重新上传', referer(), 'error');
            }
            /*设置上传路径*/
            if (!file_exists('../addons/goouc_class/upload/')) {
                mkdir('../addons/goouc_class/upload/', 0777, true);
            }
            $savePath = IA_ROOT . '/addons/goouc_class/upload/';
            /*以时间来命名上传的文件*/
            $str = date('Ymdhis');
            $file_name = $str . "." . $file_type;
            /*是否上传成功*/
            if (!copy($tmp_file, $savePath . $file_name)) {
                message('上传失败');
            }
            $objPHPExcel = PHPExcel_IOFactory::load($savePath . $file_name);
            $indata = $objPHPExcel->getSheet(0)->toArray();
            foreach ($indata as $k => $v) {
                if ($k != 0) {
                    $question_type = trim($v[0]);
                    $question = trim($v[1]);
                    $answer = $v[2];
                    $item1 = $v[3];
                    $item2 = $v[4];
                    $item3 = $v[5];
                    $item4 = $v[6];
                    $item5 = $v[7];
                    $item6 = $v[8];
                    $explain = $v[9];
                    if (empty($question_type) || empty($question) || empty($answer)) {
                        return 0;
                    }
                    $insert = [
                        'weid' => $weid,
                        'lessonid' => $lid,
                        'sonid' => $sonid,
                        'question' => $question
                    ];
                    //1 判断 2单选 3多选 4 填空  5 解答
                    if ($question_type == '单选题') {
                        $type = 2;
                        $insert['answer'] = $answer;
                    } elseif ($question_type == '多选题') {
                        $type = 3;
                        $insert['answer'] = $answer;
                    } elseif ($question_type == '判断题') {
                        $type = 1;
                        if ($answer == '正确') {
                            $insert['answer'] = 1;
                        } else {
                            $insert['answer'] = 0;
                        }
                    } elseif ($question_type == '填空题') {
                        $type = 4;
                        $insert['answer'] = $answer;
                    } elseif ($question_type == '简答题') {
                        $type = 5;
                        $insert['answer'] = $answer;
                    }
                    if ($type == 2) {
                        $itemsArray = array(['o' => 'A', 'p' => $item1], ['o' => 'B', 'p' => $item2], ['o' => 'C', 'p' => $item3], ['o' => 'D', 'p' => $item4]);
                        $insert['items'] = serialize($itemsArray);
                    }
                    if ($type == 3) {
                        $itemsArray = array(['o' => 'A', 'p' => $item1], ['o' => 'B', 'p' => $item2], ['o' => 'C', 'p' => $item3], ['o' => 'D', 'p' => $item4], ['o' => 'E', 'p' => $item5], ['o' => 'F', 'p' => $item6]);
                        $insert['items'] = serialize($itemsArray);
                    }
                    $insert['analysis'] = $explain;
                    $insert['type'] = $type;
                    $insert['isimg'] = 0;
                    $result = pdo_insert('goouc_class_practice', $insert);
                }
            }
            if ($result) {
                //如果这个课程的这个章节已经有题，也有学生做过了，那么就把学生做题状态改为没有做题，星星也要重新计算
                $sqlrecord = 'SELECT id FROM' . tablename("goouc_class_practice_record") . 'WHERE weid = :weid AND lessonid = :lessonid AND sonid = :sonid AND status = :status ';
                $recordlist = pdo_fetchall($sqlrecord, array(':weid' => $weid, ':lessonid' => $lid, ':sonid' => $sonid, ':status' => 1));
                if ($recordlist) {
                    foreach ($recordlist as $rk => $rv) {
                        pdo_update('goouc_class_practice_record', array('status' => 2), array('id' => $rv['id']));
                    }
                }
                //把获取的星星也要重新计算
                $sqlstar = 'SELECT id FROM' . tablename("goouc_class_user_star") . 'WHERE weid = :weid AND lessonid = :lessonid AND sonid = :sonid AND status = :status ';
                $starlist = pdo_fetchall($sqlstar, array(':weid' => $weid, ':lessonid' => $lid, ':sonid' => $sonid, ':status' => 1));
                if ($starlist) {
                    foreach ($starlist as $rk => $rv) {
                        pdo_update('goouc_class_user_star', array('status' => 2), array('id' => $rv['id']));
                    }
                }
                $array['op'] = 'list';
                $array['lid'] = $lid;
                $array['sonid'] = $sonid;
                $url = $this->createWebUrl('practice', $array);
                message("导入成功!", $url, "success");
            }
        }
    }
    include $this->template('web/upload_question');
} elseif ($op == 'sort') {
    if ($this->userid == $_W['uid']) {
        $message = array('success' => 0, 'mess' => $this->msg);
        echo json_encode($message);
        exit;
    }
    $id = $_GPC['id'];
    $data['sort'] = $_GPC['sort'];
    //var_dump($id); var_dump($data['order']);die;
    $res = pdo_update("goouc_class_practice", $data, array('id' => $id, 'weid' => $_W['uniacid']));
    if ($res) {
        $message = array('success' => 1, 'mess' => '修改成功');
    } else {
        $message = array('success' => 0, 'mess' => '修改失败');
    }
}
